<template>
  <div class="sales-ranking-page">
    <van-nav-bar
      title="销售排行"
      left-arrow
      @click-left="router.back()"
    />

    <!-- 时间筛选 -->
    <div class="filter-section">
      <div class="date-filter">
        <van-tabs v-model:active="timeRange" @change="handleTimeRangeChange">
          <van-tab title="今日" name="today"></van-tab>
          <van-tab title="本周" name="week"></van-tab>
          <van-tab title="本月" name="month"></van-tab>
          <van-tab title="全部" name="all"></van-tab>
        </van-tabs>
      </div>
      <div class="custom-date" v-if="timeRange === 'custom'">
        <van-date-picker
          v-model="customDateRange"
          type="range"
          title="选择日期范围"
          :min-date="new Date(2020, 0, 1)"
          :max-date="new Date()"
          @confirm="handleCustomDateConfirm"
          @cancel="timeRange = 'today'"
        />
      </div>
    </div>

    <!-- 排行切换 -->
    <div class="ranking-filter">
      <van-dropdown-menu>
        <van-dropdown-item v-model="rankingType" :options="rankingOptions" @change="handleRankingTypeChange" />
        <van-dropdown-item v-model="categoryType" :options="categoryOptions" @change="handleCategoryChange" />
      </van-dropdown-menu>
    </div>

    <!-- 排行列表 -->
    <div class="ranking-section">
      <div class="ranking-header">
        <div class="title">
          {{ categoryType === 'all' ? '全部商品' : '按分类' }}排行
          <span class="date-range">{{ formattedDateRange }}</span>
        </div>
        <div class="total-info">
          <span>总{{ rankingType === 0 ? '销量' : '金额' }}：</span>
          <span class="value">{{ rankingType === 0 ? totalQuantity + '件' : '¥' + totalAmount.toFixed(2) }}</span>
        </div>
      </div>
      
      <van-empty v-if="rankingList.length === 0" description="暂无销售数据" />
      
      <div class="ranking-list" v-else>
        <div v-for="(item, index) in rankingList" :key="item.id" class="ranking-item">
          <div class="rank-number" :class="{ 'top-three': index < 3 }">{{ index + 1 }}</div>
          <div class="item-info">
            <div class="product-image" v-if="item.image">
              <img :src="item.image" alt="product image">
            </div>
            <div class="product-details">
              <div class="name">{{ item.name }}</div>
              <div class="category" v-if="item.category">{{ item.category }}</div>
            </div>
            <div class="count">
              <span class="value">{{ rankingType === 0 ? item.quantity + '件' : '¥' + item.amount.toFixed(2) }}</span>
              <span class="percent">{{ calculatePercent(item) }}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表展示 -->
    <div class="chart-section">
      <div class="section-header">
        <div class="title">销售分布</div>
        <van-button size="small" type="primary" @click="exportData">导出数据</van-button>
      </div>
      <div class="chart-container">
        <!-- 这里可以使用echarts等图表库展示饼图或柱状图 -->
        <div class="chart-placeholder">
          <div class="pie-chart">
            <div v-for="(item, index) in topRankingItems" :key="item.id" 
                 class="pie-segment" 
                 :style="{ 
                   '--segment-color': getColorByIndex(index),
                   '--segment-percent': calculatePercent(item) + '%'
                 }">
            </div>
            <div class="pie-center">
              {{ rankingType === 0 ? '销量' : '金额' }}<br>分布
            </div>
          </div>
          <div class="chart-legend">
            <div v-for="(item, index) in topRankingItems" :key="item.id" class="legend-item">
              <div class="color-dot" :style="{ backgroundColor: getColorByIndex(index) }"></div>
              <div class="legend-name">{{ item.name }}</div>
              <div class="legend-value">{{ calculatePercent(item) }}%</div>
            </div>
            <div v-if="rankingList.length > 5" class="legend-item">
              <div class="color-dot" style="backgroundColor: #ccc"></div>
              <div class="legend-name">其他</div>
              <div class="legend-value">{{ otherPercent }}%</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'

const router = useRouter()

// 时间筛选
const timeRange = ref('today')
const customDateRange = ref<string[]>([
  new Date().toISOString().split('T')[0],
  new Date().toISOString().split('T')[0]
])

// 格式化日期显示
const formattedDateRange = computed(() => {
  switch (timeRange.value) {
    case 'today':
      return '今日'
    case 'week':
      return '本周'
    case 'month':
      return '本月'
    case 'all':
      return '全部时间'
    case 'custom':
      const startDate = formatDate(customDateRange.value[0])
      const endDate = formatDate(customDateRange.value[1])
      return `${startDate} - ${endDate}`
    default:
      return '今日'
  }
})

// 排行类型
const rankingType = ref(0)
const rankingOptions = [
  { text: '销量排行', value: 0 },
  { text: '金额排行', value: 1 }
]

// 分类筛选
const categoryType = ref('all')
const categoryOptions = [
  { text: '全部商品', value: 'all' },
  { text: '饮料', value: 'drinks' },
  { text: '方便面', value: 'noodles' },
  { text: '零食', value: 'snacks' },
  { text: '日用品', value: 'daily' }
]

// 筛选后的排行列表
const rankingList = ref([
  { id: 1, name: '康师傅红烧牛肉面', category: '方便面', quantity: 135, amount: 607.5, image: '/products/noodle1.png' },
  { id: 2, name: '统一老坛酸菜面', category: '方便面', quantity: 98, amount: 392.0, image: '/products/noodle2.png' },
  { id: 3, name: '雪碧', category: '饮料', quantity: 87, amount: 261.0, image: '/products/drink1.png' },
  { id: 4, name: '可口可乐', category: '饮料', quantity: 82, amount: 246.0, image: '/products/drink2.png' },
  { id: 5, name: '百事可乐', category: '饮料', quantity: 76, amount: 228.0, image: '/products/drink3.png' },
  { id: 6, name: '农夫山泉', category: '饮料', quantity: 73, amount: 146.0, image: '/products/water1.png' },
  { id: 7, name: '康师傅冰红茶', category: '饮料', quantity: 68, amount: 204.0, image: '/products/drink4.png' },
  { id: 8, name: '华丰方便面', category: '方便面', quantity: 65, amount: 260.0, image: '/products/noodle3.png' },
  { id: 9, name: '好丽友派', category: '零食', quantity: 62, amount: 186.0, image: '/products/snack1.png' },
  { id: 10, name: '乐事薯片', category: '零食', quantity: 58, amount: 290.0, image: '/products/snack2.png' },
  { id: 11, name: '洗发水', category: '日用品', quantity: 45, amount: 675.0, image: '/products/daily1.png' },
  { id: 12, name: '牙膏', category: '日用品', quantity: 42, amount: 336.0, image: '/products/daily2.png' }
])

// 计算总数量和总金额
const totalQuantity = computed(() => {
  return rankingList.value.reduce((total, item) => total + item.quantity, 0)
})

const totalAmount = computed(() => {
  return rankingList.value.reduce((total, item) => total + item.amount, 0)
})

// 获取前5个项目用于饼图展示
const topRankingItems = computed(() => {
  return rankingList.value.slice(0, 5)
})

// 计算其他项目的百分比
const otherPercent = computed(() => {
  if (rankingList.value.length <= 5) return 0
  
  const topItemsTotal = rankingType.value === 0
    ? topRankingItems.value.reduce((sum, item) => sum + item.quantity, 0)
    : topRankingItems.value.reduce((sum, item) => sum + item.amount, 0)
  
  const total = rankingType.value === 0 ? totalQuantity.value : totalAmount.value
  return Math.round(((total - topItemsTotal) / total) * 100)
})

// 计算每个项目的百分比
const calculatePercent = (item: any) => {
  const total = rankingType.value === 0 ? totalQuantity.value : totalAmount.value
  const value = rankingType.value === 0 ? item.quantity : item.amount
  return Math.round((value / total) * 100)
}

// 获取饼图颜色
const getColorByIndex = (index: number) => {
  const colors = ['#ee0a24', '#ff9900', '#07c160', '#1989fa', '#8a2be2']
  return colors[index % colors.length]
}

// 日期格式化
const formatDate = (date: Date): string => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 处理时间范围变化
const handleTimeRangeChange = (name: string) => {
  if (name === 'custom') {
    // 打开日期选择器
  } else {
    filterRankingData()
  }
}

// 处理自定义日期确认
const handleCustomDateConfirm = (values: Date[]) => {
  customDateRange.value = values.map(date => date.toISOString().split('T')[0])
  filterRankingData()
}

// 处理排行类型变化
const handleRankingTypeChange = () => {
  sortRankingList()
}

// 处理分类变化
const handleCategoryChange = () => {
  filterRankingData()
}

// 筛选排行数据
const filterRankingData = () => {
  // 根据时间范围和分类筛选数据
  let filteredData = [...rankingList.value]
  
  // 如果有分类筛选
  if (categoryType.value !== 'all') {
    filteredData = filteredData.filter(item => item.category === categoryOptions.find(opt => opt.value === categoryType.value)?.text)
  }
  
  // 这里应该有根据时间范围的筛选逻辑
  // 实际应用中应该从API获取不同时间范围的数据
  
  rankingList.value = filteredData
  sortRankingList()
}

// 排序排行列表
const sortRankingList = () => {
  rankingList.value.sort((a, b) => {
    if (rankingType.value === 0) {
      return b.quantity - a.quantity
    } else {
      return b.amount - a.amount
    }
  })
}

// 导出数据
const exportData = () => {
  showToast({
    type: 'loading',
    message: '正在导出数据...',
    forbidClick: true
  })
  
  setTimeout(() => {
    showToast({
      type: 'success',
      message: '数据已导出'
    })
  }, 1500)
}

// 监听时间范围变化
watch(timeRange, (newValue) => {
  if (newValue !== 'custom') {
    filterRankingData()
  }
})

// 监听分类变化
watch(categoryType, () => {
  filterRankingData()
})

onMounted(() => {
  // 初始化排序
  sortRankingList()
})
</script>

<style lang="scss" scoped>
.sales-ranking-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
  overflow-y: auto;
  padding-bottom: 20px;

  .filter-section {
    background: #fff;
    margin-bottom: 10px;
  }

  .ranking-filter {
    margin-bottom: 10px;
  }

  .ranking-section {
    background: #fff;
    margin: 0 15px 15px;
    border-radius: 12px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .ranking-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      .title {
        font-size: 16px;
        font-weight: bold;
        
        .date-range {
          font-size: 12px;
          color: #666;
          font-weight: normal;
          margin-left: 5px;
        }
      }
      
      .total-info {
        font-size: 14px;
        
        .value {
          color: #ee0a24;
          font-weight: bold;
        }
      }
    }
  }

  .ranking-list {
    .ranking-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      .rank-number {
        width: 24px;
        height: 24px;
        background: #f5f5f5;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 12px;
        font-size: 14px;
        color: #666;

        &.top-three {
          background: #ffd700;
          color: #fff;
          
          &:nth-child(1) {
            background: #ff4d4f;
          }
          
          &:nth-child(2) {
            background: #ff7a45;
          }
          
          &:nth-child(3) {
            background: #ffa940;
          }
        }
      }

      .item-info {
        flex: 1;
        display: flex;
        align-items: center;
        
        .product-image {
          width: 40px;
          height: 40px;
          margin-right: 10px;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 4px;
          }
        }
        
        .product-details {
          flex: 1;
          
          .name {
            font-size: 14px;
            margin-bottom: 2px;
          }
          
          .category {
            font-size: 12px;
            color: #999;
          }
        }

        .count {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          
          .value {
            color: #ee0a24;
            font-weight: bold;
          }
          
          .percent {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }

  .chart-section {
    background: #fff;
    margin: 0 15px;
    border-radius: 12px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      .title {
        font-size: 16px;
        font-weight: bold;
      }
    }
    
    .chart-container {
      .chart-placeholder {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 15px 0;
        
        .pie-chart {
          position: relative;
          width: 200px;
          height: 200px;
          border-radius: 50%;
          background: #f5f5f5;
          margin-bottom: 20px;
          
          .pie-segment {
            position: absolute;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            clip-path: polygon(50% 50%, 50% 0, calc(50% + var(--segment-percent)) 0, 50% 50%);
            background-color: var(--segment-color);
            transform-origin: center;
            transform: rotate(calc(var(--rotation, 0) * 3.6deg));
          }
          
          .pie-center {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 80px;
            height: 80px;
            background: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            text-align: center;
            font-size: 14px;
            color: #666;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
          }
        }
        
        .chart-legend {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          justify-content: center;
          gap: 10px;
          
          .legend-item {
            display: flex;
            align-items: center;
            margin-right: 15px;
            margin-bottom: 10px;
            
            .color-dot {
              width: 12px;
              height: 12px;
              border-radius: 50%;
              margin-right: 6px;
            }
            
            .legend-name {
              font-size: 12px;
              color: #333;
              margin-right: 5px;
              max-width: 80px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            
            .legend-value {
              font-size: 12px;
              color: #999;
            }
          }
        }
      }
    }
  }
}
</style> 